<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\auth;

interface ISession
{
  public static function login(\crcl\base\structure\Item $oProfile);
  public static function logout();

  public static function isLoggedIn();
}

class Session implements ISession
{
  const NS = 'base_auth';
  const ID = 'iIdentity';

  public static function login(\crcl\base\structure\Item $oProfile)
  {
    try
    {
      $oProfile = $oProfile->persistance()->loadFromFields($oProfile->getAuthData());
      $iIdentity = $oProfile->identity->get();
    }
    catch (\crcl\base\database\container\Exception $e)
    {
      $sMessage = 'Invalid identity.';
      if (\crcl\base\Tier::isLocal())
      {
        $sMessage .= ' (' . $e->getMessage() . ')';
      }
      throw new Exception($sMessage, Exception::ERROR_INVALID_IDENTITY,
        array('oProfile' => $oProfile));
    }

    if (\is_null($iIdentity))
    {
      throw new Exception('Invalid identity.', Exception::ERROR_INVALID_IDENTITY,
        array('oProfile' => $oProfile));
    }
    else
    {
      \crcl\base\Session::setNamespace(self::NS, self::ID, $iIdentity);
    }
  }

  public static function logout()
  {
    \crcl\base\Session::removeNamespace(self::NS, self::ID);
  }

  public static function isLoggedIn()
  {
    $bReturn = \FALSE;

    if (\crcl\base\Session::existsNamespace(self::NS, self::ID))
    {
      if (!\is_null(\crcl\base\Session::getNamespace(self::NS, self::ID)))
      {
        $bReturn = \TRUE;
      }
    }
    return $bReturn;
  }

  public static function getId()
  {
    return \crcl\base\Session::getNamespace(self::NS, self::ID);
  }

  public static function get($sKey)
  {
    return \crcl\base\Session::getNamespace(self::NS, $sKey);
  }
}